package com.example.myletcodelearing.one

/**
 * @author tgw
 * @date 2022/11/6
 * @describe https://leetcode.cn/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode-solution-4n3u/
 */
fun main(args: Array<String>) {
    val aa = Solution6().convert("qwertyuiopqe", 3)
    val aa2 = Solution6().convert2("qwertyuiopqe", 3)
    println(aa)
    println(aa2)
}


private class Solution6 {

    fun convert(s: String, numRows: Int): String {
        val n = s.length
        if (numRows == 1 || numRows >= n) {
            return s
        }
        val mat = arrayOfNulls<StringBuffer>(numRows)
        for (i in 0 until numRows) {
            mat[i] = StringBuffer()
        }
        var i = 0
        var x = 0
        val t = numRows * 2 - 2
        while (i < n) {
            mat[x]!!.append(s[i])
            if (i % t < numRows - 1) {
                ++x
            } else {
                --x
            }
            ++i
        }
        val ans = StringBuffer()
        for (row in mat) {
            ans.append(row)
        }
        return ans.toString()
    }

    fun convert2(s: String, numRows: Int): String {
        val n: Int = s.length
        if (numRows == 1 || numRows >= n) {
            return s
        }
        val t = numRows * 2 - 2
        val ans = StringBuffer()
        for (i in 0 until numRows) { // 枚举行
            var j = 0
            while (j < n - i) {
                // 枚举每个周期的起始索引
                ans.append(s[i + j]) // 当前周期的第一个字符
                if (i > 0 && i < numRows - 1 && j + t - i < n)
                    ans.append(s[j + t - i]) // 枚举当前周期的第二个字符
                j += t
            }
        }
        return ans.toString()
    }
}